/*
 * This program is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Affero General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3, 
 * the Appropriate Legal Notices must display the following words on all interactive user interfaces: 
 * "Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved."
 */

function GetUserID(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/GetUserID');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							sUSER_ID = result.d;
							callback(1, null);
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'GetUserID'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'GetUserID'));
	}
}

function GetUserName(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/GetUserName');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							sUSER_NAME = result.d;
							callback(1, null);
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'GetUserName'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'GetUserName'));
	}
}

function GetTeamID(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/GetTeamID');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							sTEAM_ID = result.d;
							callback(1, null);
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'GetTeamID'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'GetTeamID'));
	}
}

function GetTeamName(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/GetTeamName');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							sTEAM_NAME = result.d;
							callback(1, null);
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'GetTeamName'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'GetTeamName'));
	}
}

function GetUserLanguage(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/GetUserLanguage');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							sUSER_LANG = result.d;
							callback(1, null);
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'GetUserLanguage'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'GetUserLanguage'));
	}
}

function GetUserProfile(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/GetUserProfile');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							sUSER_ID          = result.d.USER_ID  ;
							sUSER_NAME        = result.d.USER_NAME;
							sTEAM_ID          = result.d.TEAM_ID  ;
							sTEAM_NAME        = result.d.TEAM_NAME;
							sUSER_LANG        = result.d.USER_LANG;
							sUSER_DATE_FORMAT = result.d.USER_DATE_FORMAT;
							sUSER_TIME_FORMAT = result.d.USER_TIME_FORMAT;
							callback(1, null);
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'GetUserProfile'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'GetUserProfile'));
	}
}

function IsAuthenticated(callback)
{
	if ( !ValidateCredentials() )
	{
		callback(-1, 'Invalid connection information.');
		return;
	}
	var xhr = CreateSplendidRequest('Rest.svc/IsAuthenticated');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							if ( result.d == true )
							{
								if ( sUSER_ID == '' )
								{
									GetUserID(function(status, message)
									{
										if ( status == 1 )
										{
											GetUserLanguage(function(status, message)
											{
												if ( status == 1 )
												{
													// 11/28/2011 Paul.  Reset after getting the language. 
													// We are noticing a CONFIG is null error when transitioning from offline to online. 
													SplendidCache.Reset();
													callback(1, '');
												}
												else
												{
													callback(status, message);
												}
											});
										}
										else
										{
											callback(status, message);
										}
									});
								}
								else
								{
									callback(1, '');
								}
							}
							else
							{
								sUSER_ID = '';
								callback(0, '');
							}
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else if ( result.status == 0 && bIS_OFFLINE )
					{
						// 09/28/2011 Paul.  Instead of returning an error, offline should return success. 
						callback(1, 'Offline');
					}
					else
					{
						if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'IsAuthenticated'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		//alert('IsAuthenticated: ' + e.message);
		//callback(-1, SplendidError.FormatError(e, 'IsAuthenticated'));
		// 11/28/2011 Paul.  xhr.send is throwing an exception on IE8 when working offline. 
		// The download of the specified resource has failed. 
		//callback(-1, '');
		if ( sUSER_ID === undefined || sUSER_ID == '' || sUSER_ID == null )
			result = { 'status': 0, 'd': false };
		else
			result = { 'status': 0, 'd': true };
		callback(result);
	}
}

function Login(callback)
{
	if ( !ValidateCredentials() )
	{
		callback(-1, 'Invalid connection information.');
		return;
	}
	var xhr = CreateSplendidRequest('Rest.svc/Login');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							if ( result.d.length == 36 )
							{
								SplendidCache.Reset();
								sUSER_ID = result.d;
								GetUserLanguage(function(status, message)
								{
									if ( status == 1 )
									{
										callback(1, null);
									}
									else
									{
										callback(status, message);
									}
								});
							}
							else
								callback(-1, 'Login should return Guid.');
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else
					{
						if ( result.status == 0 )
							callback(0, result.ExceptionDetail.Message);
						else if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'Login'));
				}
			});
		}
	}
	try
	{
		xhr.send('{"UserName": ' + JSON.stringify(sUSER_NAME) + ', "Password": ' + JSON.stringify(sPASSWORD) + ', "Version": "6.0"}');
	}
	catch(e)
	{
		//alert('Login: ' + e.message);
		callback(-1, SplendidError.FormatError(e, 'Login'));
	}
}

function AuthenticatedMethod(callback)
{
	if ( !ValidateCredentials() )
	{
		ShowOptionsDialog();
	}
	else
	{
		IsAuthenticated(function(status, message)
		{
			if ( status == 1 )
			{
				// 08/30/2011 Paul.  Now may be a good time to run SplendidInit. 
				// 10/04/2011 Paul.  Return the user information for the Safari Extension. 
				callback(1, { 'sUSER_ID': sUSER_ID, 'sUSER_NAME': sUSER_NAME, 'sUSER_LANG': sUSER_LANG, 'sUSER_DATE_FORMAT': sUSER_DATE_FORMAT, 'sUSER_TIME_FORMAT': sUSER_TIME_FORMAT, 'sFULL_NAME': sFULL_NAME, 'sTEAM_ID': sTEAM_ID, 'sTEAM_NAME': sTEAM_NAME, 'bIS_OFFLINE': bIS_OFFLINE, 'bENABLE_OFFLINE': bENABLE_OFFLINE } );
			}
			else if ( status == 0 )
			{
				// 12/08/2011 Paul.  IE7 defines window.XMLHttpRequest but not window.localStorage. 
				if ( window.sessionStorage && (sPASSWORD === undefined || sPASSWORD == '' || sPASSWORD == null) )
				{
					// 11/28/2011 Paul.  We need to save the user name and password so that we can re-authenticate when the connection is restored. 
					sPASSWORD         = sessionStorage['PASSWORD'        ];
					sUSER_ID          = sessionStorage['USER_ID'         ];
					sUSER_NAME        = sessionStorage['USER_NAME'       ];
					sTEAM_ID          = sessionStorage['TEAM_ID'         ];
					sTEAM_NAME        = sessionStorage['TEAM_NAME'       ];
					sUSER_LANG        = sessionStorage['USER_LANG'       ];
					sUSER_DATE_FORMAT = sessionStorage['USER_DATE_FORMAT'];
					sUSER_TIME_FORMAT = sessionStorage['USER_TIME_FORMAT'];
				}
				// 10/14/2011 Paul.  Make sure that we do not attempt to login if we do not have a password as it will eventually lock-out the user. 
				if ( sAUTHENTICATION == 'CRM' && !(sPASSWORD === undefined || sPASSWORD == '' || sPASSWORD == null) )
				{
					Login(function(status, message)
					{
						if ( status == 1 )
						{
							// 08/30/2011 Paul.  Now may be a good time to run SplendidInit. 
							// 10/04/2011 Paul.  Return the user information for the Safari Extension. 
							callback(1, { 'sUSER_ID': sUSER_ID, 'sUSER_NAME': sUSER_NAME, 'sUSER_LANG': sUSER_LANG, 'sUSER_DATE_FORMAT': sUSER_DATE_FORMAT, 'sUSER_TIME_FORMAT': sUSER_TIME_FORMAT, 'sFULL_NAME': sFULL_NAME, 'sTEAM_ID': sTEAM_ID, 'sTEAM_NAME': sTEAM_NAME, 'bIS_OFFLINE': bIS_OFFLINE, 'bENABLE_OFFLINE': bENABLE_OFFLINE } );
						}
						else
						{
							callback(status, message);
						}
					});
				}
				else
				{
					callback(status, 'Failed to authenticate. Please login again. ');
				}
			}
			else
			{
				callback(status, message);
			}
		});
	}
}

function IsOnline(callback)
{
	var xhr = CreateSplendidRequest('Rest.svc/Version', 'POST');
	xhr.onreadystatechange = function()
	{
		if ( xhr.readyState == 4 )
		{
			GetSplendidResult(xhr, function(result)
			{
				try
				{
					if ( result.status == 200 )
					{
						if ( result.d !== undefined )
						{
							callback(1, '');
						}
						else
						{
							callback(-1, xhr.responseText);
						}
					}
					else if ( result.status == 0 )
					{
						callback(0, '');
					}
					else
					{
						if ( result.ExceptionDetail !== undefined )
							callback(-1, result.ExceptionDetail.Message);
						else
							callback(-1, xhr.responseText);
					}
				}
				catch(e)
				{
					callback(-1, SplendidError.FormatError(e, 'IsOnline'));
				}
			});
		}
	}
	try
	{
		xhr.send();
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'IsOnline'));
	}
}


